import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

/// 请求方法:枚举类型
enum DioMethod {
  get,
  post,
  put,
  delete,
  patch,
  head,
}

class Request {
  static Request? _instance;
  static late CookieJar cookieJar;
  static Future<Dio>? _dioFuture;

  factory Request() => _instance ?? Request._internal();
  static Request? get instance => _instance ?? Request._internal();

  Request._internal() {
    _instance = this;
    _dioFuture = _initDio();
  }

  Future<Dio> _initDio() async {
    BaseOptions options = BaseOptions(
      baseUrl: 'https://www.wanandroid.com',
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 5),
      contentType: Headers.formUrlEncodedContentType
    );

    Dio dio = Dio(options);

    // 设置 Cookie
    // kIsWeb ? await getLibraryDirectory() : web中设置Cookie报错解决
    // final appDocDir = kIsWeb ? await getLibraryDirectory() :  await getApplicationDocumentsDirectory();
    
    
    
    // final appDocDir = await getApplicationDocumentsDirectory();
    // final appDocPath = appDocDir.path;
    // cookieJar = PersistCookieJar(
    //   ignoreExpires: true,
    //   storage: FileStorage(appDocPath + "/.cookies/")
    // );
    // // 将CookieManager添加到Dio的拦截器中
    // dio.interceptors.add(CookieManager(cookieJar));

    // 添加其他拦截器
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: _onRequest,
      onResponse: _onResponse,
      onError: _onError
    ));

    // /// 开启日志打印
    // /// 需要打印日志的接口在接口请求前 Request.instance?.openLog();
    // dio.interceptors.add(
    //   LogInterceptor(responseHeader: false, responseBody: true)
    // );

    return dio;
  }

  /// 请求拦截器
  void _onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 对非open的接口的请求参数全部增加userId
    // if (!options.path.contains("open")) {
    //   options.queryParameters["userId"] = "xxx";
    // }
    // 头部添加token
    // options.headers["token"] = "xxx";
    // 更多业务需求
    handler.next(options);
    // super.onRequest(options, handler);
  }

  /// 响应拦截器
  void _onResponse( Response response, ResponseInterceptorHandler handler) async {
    // 请求成功是对数据做基本处理
    if (response.statusCode == 200) {
      // 处理成功的响应
      // print("响应结果: $response");
    } else {
      // 处理异常结果
      // print("响应异常: $response");
    }
    handler.next(response);
  }

  /// 错误处理: 网络错误等
  void _onError(DioException error, ErrorInterceptorHandler handler) {
    handler.next(error);
  }

  Future<T> request<T>(
    String path, {
    DioMethod method = DioMethod.get,
    Map<String, dynamic>? params,
    dynamic data,
    CancelToken? cancelToken,
    Options? options,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    const _methodValues = {
      DioMethod.get: 'get',
      DioMethod.post: 'post',
      DioMethod.put: 'put',
      DioMethod.delete: 'delete',
      DioMethod.patch: 'patch',
      DioMethod.head: 'head'
    };

    options ??= Options(method: _methodValues[method]);

    try {
      // Wait for Dio to be fully initialized before making the request
      final dio = await _dioFuture!;

      Response response = await dio.request(
        path,
        data: data,
        queryParameters: params,
        cancelToken: cancelToken,
        options: options,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress
      );
      return response.data;
    } on DioException catch (e) {
      print("发送请求异常: $e");
      rethrow;
    }
  }
}